import Vue from 'vue'
import Axios from 'axios'

const axios = Axios.create()

axios.interceptors.request.use(
  config => {
    config.baseURL = process.env.VUE_APP_API_DOMAIN

    if (config.params === undefined) config.params = {}
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    const $tips = Vue.prototype.$tips
    const code = parseInt(response.data.code)
    if (response.status !== 200) {
      $tips({ message: 'Server Error!', type: 'error' })
      return Promise.reject(new Error('Server Error!'))
    } else if (code && code !== 1000) {
      return Promise.reject(response.data)
    } else {
      return response.data
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default axios
